package com.doctor.net;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import android.content.Context;
import android.os.Handler;
import android.os.Message;

import com.doctor.comm.ConstConfig;
import com.doctor.comm.ImageHelper;

public class GetDataThread {

	private Context context;
	private ThreadPoolManager threadPoolManager;
	private List<BaseTask> record = new Vector<BaseTask>();
	private static GetDataThread getDataThread;
	
	private GetDataThread(Context context){
		super();
		this.context=context;
		threadPoolManager=ThreadPoolManager.getInstance();
	}
	
	public static GetDataThread getInstance(Context context){
		if (getDataThread==null) {
			getDataThread=new GetDataThread(context);
		}
		return getDataThread;
	}
	
	public interface DataCallback<T> {
		public void processData(T paramObject, boolean paramBoolean);
	}
	
	public void getDataFromServer(String method, String decode, RequestParams params, DataCallback callBack) {
//		showProgressDialog();
		BaseHandler handler = new BaseHandler(context, callBack, params);
		BaseTask taskThread = new BaseTask(context, decode, params, handler,method);
		record.add(taskThread);
		threadPoolManager.addTask(taskThread);
	}
	
	public void getDataFromServer(String method, RequestParams params, DataCallback callBack) {
		getDataFromServer(method, null, params, callBack);
	}
	
	
	class BaseHandler extends Handler {
 		private Context context;
		private DataCallback callBack;
		private RequestParams params;

		public BaseHandler(Context context, DataCallback callBack, RequestParams params) {
			this.context = context;
			this.callBack = callBack;
			this.params = params;
		}

		public void handleMessage(Message msg) {
//			closeProgressDialog();
//			if (msg.what == ConstConfig.SUCCESS) {
//				if (msg.obj == null) {
//					CommonUtil.showInfoDialog(context, getString(R.string.net_error));
//					LoadingTip.hideDialog();
//					Toast.makeText(context, "服务器连接错误！", Toast.LENGTH_LONG).show();
//				} else {
					callBack.processData(msg.obj, true);
//				}
//			} else if (msg.what == ConstConfig.NET_FAILED) {
//				CommonUtil.showInfoDialog(context, getString(R.string.net_error));
//			}
			
//			Logger.d(TAG, "recordSize:" + record.size());
		}
	}
	
	
	class BaseTask implements Runnable {
		private Context context;
		private RequestParams params;
		private Handler handler;
		private String method;
		private String decode;

		public BaseTask(Context context, String decode,RequestParams params, Handler handler, String method) {
			this.context = context;
			this.params = params;
			this.handler = handler;
			this.method=method;
			this.decode = decode;
		}

		@Override
		public void run() {
			Object obj = null;
			Message msg = Message.obtain();
			try {
//				if (NetUtil.hasNetwork(context)) {
//					obj = NetUtil.get(params);
					if (ConstConfig.GET.equals(method)) {
						obj = NetUtil.get(decode, params);
					} else if (ConstConfig.POST.equals(method)) {
						obj = NetUtil.post(decode, params);
					}	
//					if (obj instanceof Status) {
//						Intent intent = new Intent(BaseWapperActivity.this, LoginActivity.class);
//						intent.putExtra("notlogin", "notlogin");
//						startActivityForResult(intent, NOT_LOGIN);
//					} else {
						msg.what = ConstConfig.SUCCESS;
						msg.obj = obj;
						handler.sendMessage(msg);
						record.remove(this);
//					}
//				} else {
//					msg.what = ConstConfig.NET_FAILED;
//					msg.obj = obj;
//					handler.sendMessage(msg);
//					record.remove(this);
//				}
			} catch (Exception e) {
				if(null != record) {
					record.remove(this);
				}
				throw new RuntimeException(e);
			}
		}

	}
	
	
	/**
	 * 上传图片(可上传多张图片)
	 * @param params
	 * @return
	 */
	public String postImg(RequestParams params){
		HttpURLConnection httpUrlConn = null;
		
		String end = "\r\n";
		String twoHyphens = "--";
		String boundary = "*****";
		
		Map<String, String> map=params.requestMap;
		try {
			URL url=new URL(params.requestUrl);
			httpUrlConn = (HttpURLConnection) url.openConnection();
			httpUrlConn.setDoInput(true);
			httpUrlConn.setDoOutput(true);
			httpUrlConn.setRequestMethod("POST");
			httpUrlConn.setRequestProperty("Connection", "Keep-Alive");
			httpUrlConn.setRequestProperty("Charset", "UTF-8");
			httpUrlConn.setUseCaches(false);
			httpUrlConn.setConnectTimeout(10000);  //连接超时10秒
			httpUrlConn.setReadTimeout(20000);  //传输数据超时20秒
			httpUrlConn.setRequestProperty("Content-Type","multipart/form-data;boundary=" + boundary);
			
			DataOutputStream out=new DataOutputStream(httpUrlConn.getOutputStream());
			
			int i=0;
			for (String key : map.keySet()) {
				if (key.startsWith("pic")) {
					//图片参数，取出每一张图片写入输出流里
					String imgPath=map.get(key);
					File imgFile=new File(imgPath);
					if(!imgFile.exists() || !imgFile.isFile())
						continue;
					String imgType = ImageHelper.getImageType(imgFile);
					if (imgType == null) {
						//无法识别常用图片格式则从图片名字上截取格式
						int formatIndex = imgPath.lastIndexOf(".");
						if (formatIndex + 1 < imgPath.length()) {
							imgType = imgPath.substring(formatIndex + 1);
						}
					}
					if (imgType == null) {
						continue;
					}
						
					imgType = "." + imgType;
					out.writeBytes(twoHyphens + boundary + end);
					out.writeBytes("Content-Disposition: form-data; name=\"pic" + (i + 1) + "\";filename=\"" + "pic" + (i + 1) + imgType + "\"" + end);
					out.writeBytes(end);
					InputStream imgInput=new FileInputStream(imgFile);
					int len=0;
					byte[] array=new byte[1024 * 1024];		
					while ((len=imgInput.read(array))!=-1 ) {
						out.write(array,0,len);
					}
					imgInput.close();
					
					out.writeBytes(end);
					i++;
					
				} else {
					//文本参数
					out.writeBytes(twoHyphens + boundary + end);
					out.writeBytes("Content-Disposition: form-data; name=\""+ key+"\""+end);
					out.writeBytes(end);
					//对参数值进行utf-8编码
					out.write(map.get(key).getBytes("utf-8"));
					out.writeBytes(end);
				}
			}
			//写入数据结束标志
			out.writeBytes(twoHyphens + boundary + twoHyphens + end);
			out.flush();
			
			InputStream in = httpUrlConn.getInputStream();
			BufferedReader buffer = new BufferedReader(new InputStreamReader(in));
			StringBuffer sb=new StringBuffer();
			String line;
			while ((line = buffer.readLine()) != null) {
				sb.append(line);
			}
			in.close();
			out.close();
			return sb.toString();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {
			//关闭连接释放资源
			httpUrlConn.disconnect();
		}
		return null;
	}
	
	
}
